import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserActionService } from 'src/user-action/user-action.service';
import { UserService } from 'src/user/user.service';

@Injectable()
export class AuthService {
  constructor(
    private jwtService: JwtService,
    private userService: UserService,
    private userActionService: UserActionService,
  ) {}

  async signIn(
    email: string,
    password: string,
    platform: string,
    ip: string,
  ): Promise<{ access_token: string }> {
    const user = await this.userService.findUser(email, password);
    if (user === null) {
      throw new UnauthorizedException();
    }
    await this.userActionService.create({
      userId: user.id,
      ip: ip,
      info: '登录',
      platform: platform,
    });
    const payload = { userId: user.id, username: user.username };

    return {
      access_token: await this.jwtService.signAsync(payload),
      ...user,
    };
  }
}
